package api

import (
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
)

type Auth struct {
	Username string `json:"userName" binding:"required"`
	Password string `json:"password" binding:"required"`
	AuthType string `json:"type" binding:"required"`
}

type ResData map[string]interface{}

func GetAuth(c *gin.Context) {
	var user Auth
	if err := c.BindJSON(&user); err != nil {
		log.Println(err)
		return
	}

	data := ResData{}

	isExist, userR := models.CheckAuth(user.Username, user.Password)
	if isExist {
		token, err := util.GenerateToken(strconv.Itoa(int(userR.ID)))
		if err != nil {
			data["status"] = "error"
			data["message"] = "generate token error"
			data["currentAuthority"] = "guest"
		} else {
			if err := models.PutSession(userR.ID, userR.Role); err != nil {
				data["status"] = "error"
				data["message"] = "put session error"
				data["currentAuthority"] = "guest"
			} else {
				data["status"] = "ok"
				data["message"] = token
				data["currentAuthority"] = userR.Role
			}
		}
	} else {
		data["status"] = "error"
		data["message"] = "user not found"
		data["currentAuthority"] = "guest"
	}
	data["type"] = user.AuthType
	c.JSON(http.StatusOK, data)
}
